<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商丘学院智慧农业数字中心</title>
    <link rel="stylesheet" href="./css/reset.css">
    <link rel="stylesheet" href="./css/new_index.css">
    <!-- 引入JSMpeg库用于播放RTSP视频流 -->
    <script src="https://jsmpeg.com/jsmpeg.min.js"></script>
    <style>
    .nav {
        width: 100%;
        height: 10%;
        font-size: 2vw;
        text-align: center;
        line-height: 100%;
        color: #0efcff;
        letter-spacing: .4vw;
        background: url(./img/nav.png) no-repeat;
        background-size: 100% 100%;
    }

    .nav_btn {
        width: 100%;
        height: 8%;
        /* background-color: pink; */
        display: -webkit-flex;
        display: -moz-flex;
        -webkit-flex-direction: row;
        -webkit-justify-content: space-between;
        -moz-flex-direction: row;
        -moz-justify-content: space-between;
    }

    .btn_left,
    .btn_right {
        width: 40%;
        height: 100%;
        display: -webkit-flex;
        display: -moz-flex;
        -webkit-flex-direction: row;
        -webkit-align-items: center;
        -moz-flex-direction: row;
        -moz-align-items: center;
    }

    .btn_list {
        width: 24%;
        height: 60%;
        font-size: .8vw;
        text-align: center;
        line-height: 100%;
        color: #fff;
        position: relative;
        cursor: pointer;
    }

    .btn_left a,
    .btn_right a {
        display: inline-block;
    }

    .btn_left a:nth-child(2) {
        margin: 0 .6vw;
    }

    .btn_left a:nth-child(4) {
        margin-left: .6vw;
    }

    .btn_right a:nth-child(2) {
        margin: 0 .6vw;
    }

    .btn_right a:nth-child(4) {
        margin-left: .6vw;
    }

    .btn_list:before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        border: 1px solid #6176AF;
        transform: skewX(-38deg);
    }

    .btn_list:hover::before {
        border-color: #0efcff;
        box-shadow: 1px 1px 3px 1px #0efcff inset;
    }

    .listActive:before {
        border-color: #0efcff;
        box-shadow: 1px 1px 3px 1px #0efcff inset;
    }

    .content {
        position: relative;
        width: 97%;
        height: 87%;
        margin: auto;
        /* background: white; */
    }

    .baseBox {
        position: relative;
        float: left;
        width: 48.8%;
        height: 32.3%;
        border: 1px solid #6176AF;
        background: rgba(11, 21, 44, 0.60);
        border-radius: 5px;
    }

    .baseHeightBox {
        height: 100%;
    }

    .baseCenterBox {
        margin: 1.5% 0;
    }

    .leftBox {
        float: left;
        height: 100%;
        width: 34.5%;
        /* background: yellow; */
    }

    .rightBox {
        float: left;
        height: 100%;
        width: 34.5%;
    }

    .centerBox {
        position: relative;
        float: left;
        width: 30%;
        height: 100%;
        margin: 0 .5%;
        /* background: red; */
    }

    .marginLeft {
        margin-left: 1.5%;
    }

    /* 边框描边 */
    .leftTopLine1 {
        position: absolute;
        top: 0;
        left: -1px;
        height: 1vw;
        width: 2px;
        background: #0efcff;
    }

    .leftTopLine2 {
        position: absolute;
        top: -1px;
        left: 0;
        height: 2px;
        width: 1vw;
        background: #0efcff;
    }

    .rightTopLine1 {
        position: absolute;
        top: 0;
        right: -1px;
        height: 1vw;
        width: 2px;
        background: #0efcff;
    }

    .rightTopLine2 {
        position: absolute;
        top: -1px;
        right: 0;
        height: 2px;
        width: 1vw;
        background: #0efcff;
    }

    .leftBottomLine1 {
        position: absolute;
        bottom: 0;
        left: -1px;
        height: 1vw;
        width: 2px;
        background: #0efcff;
    }

    .leftBottomLine2 {
        position: absolute;
        bottom: -1px;
        left: 0;
        height: 2px;
        width: 1vw;
        background: #0efcff;
    }

    .rightBottomLine1 {
        position: absolute;
        bottom: 0;
        right: -1px;
        height: 1vw;
        width: 2px;
        background: #0efcff;
    }

    .rightBottomLine2 {
        position: absolute;
        bottom: -1px;
        right: 0;
        height: 2px;
        width: 1vw;
        background: #0efcff;
    }

    .boxTitle {
        font-size: .8vw;
        width: 38%;
        margin-top: 1vw;
        text-align: center;
        color: #0efcff;
    }

    .right {
        float: right;
    }

    .baseBoxLeft {
        width: 30%;
        height: 95%;
        position: relative;
    }

    .baseBoxRight {
        width: 68%;
        height: 100%;
    }

    .baseBoxLeft .first_border {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
    }

    .firstBox {
        position: relative;
        z-index: 999;
        width: 80%;
        height: 80%;
        margin: 6% auto 0;
    }

    .pic {
        width: 100%;
        height: 30%;
        position: relative;
    }

    .first_top1 {
        position: absolute;
        width: 45%;
        height: 90%;
        top: 0;
        left: 0;
    }

    .first_top2 {
        position: absolute;
        width: 45%;
        height: 90%;
        top: 0;
        right: 0;
    }

    .picText {
        width: 100%;
        height: 20%;
        font-size: .6vw;
        line-height: 200%;
        color: #0efcff;
    }

    .text_second {
        float: right;
    }

    #canvas {
        display: block;
        margin: 0 auto;
        width: 10vw;
        height: 5vw;
    }

    .progress {
        position: relative;
    }

    .progress img {
        width: 12.5vw;
        height: 2vw;
        position: absolute;
        top: .4vw;
        right: -.2vw;
    }

    .progress .disease {
        position: absolute;
        top: .7vw;
        left: .5vw;
        color: #fff;
        font-size: .8vw;
    }

    .progress .similar {
        position: absolute;
        top: .8vw;
        left: 3vw;
        color: #0efcff;
        font-size: .5vw;
    }

    /* 返回图标 */
    .navLeft {
        position: absolute;
        top: 5%;
        left: 35%;
        width: 3.5%;
        height: 8%;
        z-index: 999;
    }

    .navLeft>img {
        width: 100%;
        height: 100%;
    }

    .greenhouse-monitor {
        position: relative;
        width: 100%;
        height: 100%;
    }

    .monitor-main {
        position: relative;
        width: 96%;
        height: 78%;
        margin: 1% auto 0;
        border: 1px solid #00f5ff;
        border-radius: 4px;
        overflow: hidden;
    }

    .monitor-status {
        position: absolute;
        top: 1%;
        left: 1%;
        color: #0efcff;
        font-size: 0.6vw;
        z-index: 2;
        background: rgba(0, 0, 0, 0.5);
        padding: 2px 8px;
        border-radius: 3px;
    }

    .monitor-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .monitor-info {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        background: rgba(0, 0, 0, 0.6);
        color: #fff;
        padding: 5px 10px;
        font-size: 0.6vw;
        display: flex;
        justify-content: space-between;
    }

    .monitor-location {
        font-weight: bold;
    }

    .monitor-time {
        color: #0efcff;
    }

    .monitor-cameras {
        position: absolute;
        bottom: 1%;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        gap: 10px;
        z-index: 2;
    }

    .camera-item {
        width: 4vw;
        height: 3vw;
        border: 1px solid #666;
        border-radius: 3px;
        overflow: hidden;
        cursor: pointer;
        background: rgba(0, 0, 0, 0.7);
    }

    .camera-item.active {
        border-color: #0efcff;
        box-shadow: 0 0 8px #0efcff;
    }

    .camera-item img {
        width: 100%;
        height: 70%;
        object-fit: cover;
    }

    .camera-item span {
        display: block;
        font-size: 0.5vw;
        color: #fff;
        text-align: center;
        line-height: 30%;
        padding-top: 2px;
    }

    .monitor-data {
        width: 100%;
        height: 5%;
        background-color: rgba(0, 0, 0, 0.4);
        display: flex;
        align-items: center;
        justify-content: space-around;
        padding: 0 20px;
    }

    .data-item {
        display: flex;
        align-items: center;
        width: 16%;
    }

    .data-label {
        font-size: 0.65vw;
        color: #ccc;
        margin-right: 8px;
    }

    .data-value {
        font-size: 0.7vw;
        color: #fff;
        font-weight: 500;
        margin-right: 8px;
    }

    .data-status {
        font-size: 0.6vw;
        padding: 1px 6px;
        border-radius: 3px;
    }

    .data-status.normal {
        background-color: rgba(0, 255, 0, 0.3);
        color: #0f0;
    }

    .data-status.warning {
        background-color: rgba(255, 165, 0, 0.3);
        color: #ffa500;
    }

    .data-status.error {
        background-color: rgba(255, 0, 0, 0.3);
        color: #f00;
    }

    /* ---public---- */
    .centerBox {
        width: 75%;
        margin-right: 15px;
        background: transparent;
    }

    .boxFont {
        font-size: 1.2vw;
    }

    .centerMainBox1 {
        width: 100%;
        height: 60.5%;
    }

    .centerMainBox2 {
        width: 100%;
        height: 38%;
        position: relative;
        margin-top: 15px;
    }

    .centerMainBox2 .first_border {
        position: absolute;
        width: 100%;
        height: 100%;
    }

    .boxTitle2 {
        width: 100%;
        height: 10%;
        font-size: .6vw;
        text-align: center;
        line-height: 10%;
        margin-top: 1vw;
        color: #0efcff;
    }

    .contList {
        position: relative;
        width: 70%;
        height: 8vw;
        margin: 1vw auto 0;

    }

    .content1 li {
        display: none;
    }

    .baseBox {
        width: 100%;
        border: none;
        background: none;
    }

    .boxTitle {
        font-size: .8vw;
        width: 38%;
        margin-top: 1vw;
        text-align: center;
    }

    .right {
        float: right;
    }

    .baseBoxLeft {
        width: 30%;
        height: 95%;
        position: relative;
    }

    .baseBoxRight {
        width: 68%;
        height: 100%;
    }

    .baseBoxLeft .first_border {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
    }

    .baseBox1,
    .baseBox2,
    .baseBox3 {
        position: relative;
    }

    .baseBox1 .hardware,
    .baseBox2 img,
    .baseBox3 img {
        position: absolute;
        width: 100%;
        height: 100%;
    }

    .csbaseBox1 {
        position: relative;
        z-index: 999;
    }

    #canvas {
        display: block;
        margin: 0 auto;
        width: 10vw;
        height: 5vw;
    }

    .progress {
        position: relative;
    }

    .progress img {
        width: 12.5vw;
        height: 2vw;
        position: absolute;
        top: .4vw;
        right: -.2vw;
    }

    .progress .disease {
        position: absolute;
        top: .7vw;
        left: .5vw;
        color: #fff;
        font-size: .8vw;
    }

    .progress .similar {
        position: absolute;
        top: .8vw;
        left: 3vw;
        color: #0efcff;
        font-size: .5vw;
    }

    /* 返回图标 */
    .navLeft {
        position: absolute;
        top: 5%;
        left: 35%;
        width: 3.5%;
        height: 8%;
        z-index: 999;
    }

    .navLeft>img {
        width: 100%;
        height: 100%;
    }

    /* 天气预报样式 */
    .weather-forecast {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        color: #ffffff; /* 改为白色 */
        font-size: 0.8vw;
        z-index: 1000;
        padding: 20px;
        box-sizing: border-box;
    }

    .weather-header {
        text-align: center;
        font-size: 1.2vw;
        color: #0efcff;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #0efcff;
    }

    .weather-current {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        align-items: center;
    }

    .weather-temp {
        font-size: 2.5vw;
        font-weight: bold;
        color: #0efcff;
    }

    .weather-description {
        text-align: right;
        font-size: 1vw;
        color: #ffffff; /* 改为白色 */
    }

    .weather-description div {
        color: #ffffff; /* 改为白色 */
    }

    .weather-details {
        display: flex;
        justify-content: space-between;
        font-size: 0.9vw;
        margin-bottom: 20px;
        color: #ffffff; /* 改为白色 */
    }

    .weather-details span {
        color: #0efcff;
    }

    .weather-forecast-list {
        margin-top: 10px;
        border-top: 1px solid rgba(14, 252, 255, 0.3);
        padding-top: 10px;
    }

    .forecast-item {
        display: flex;
        justify-content: space-between;
        margin: 8px 0;
        font-size: 0.9vw;
        color: #ffffff; /* 改为白色 */
    }

    .forecast-date {
        width: 25%;
        color: #ffffff; /* 改为白色 */
    }

    .forecast-weather {
        width: 40%;
        text-align: center;
        color: #ffffff; /* 改为白色 */
    }

    .forecast-temp {
        width: 35%;
        text-align: right;
        color: #0efcff;
        white-space: nowrap;
    }
    </style>
</head>

<body>
    <div class="main">
        <div class="nav">商丘学院智慧农业数字中心</div>
        <div class="nav_btn">
            <div class="btn_left">
                <!--                <a href="dataMonitor.html">-->
                <!--                    <div class="btn_list listActive">主页</div>-->
                <!--                </a>-->
                <!--                <a href="land_flow.html">-->
                <!--                    <div class="btn_list">土地流转</div>-->
                <!--                </a>-->
                <!--                <a href="sky.html">-->
                <!--                    <div class="btn_list">空天地</div>-->
                <!--                </a>-->
                <!--                <a href="production_testing.html">-->
                <!--                    <div class="btn_list">生长监测</div>-->
                <!--                </a>-->
            </div>
            <div class="btn_right">
                <!--                <a href="production.html">-->
                <!--                    <div class="btn_list">生产加工</div>-->
                <!--                </a>-->
                <!--                <a href="warehousing_management.html">-->
                <!--                    <div class="btn_list">仓储管理</div>-->
                <!--                </a>-->
                <!--                <a href="circulationSales.html">-->
                <!--                    <div class="btn_list">流通销售</div>-->
                <!--                </a>-->
                <!--                <a href="index.html">-->
                <!--                    <div class="btn_list">数据中心</div>-->
                <!--                </a>-->
            </div>
        </div>
        <div class="content">

            <div class="centerBox">
                <div class="baseBox centerMainBox1" style="height:70%">
                    <div class="baseBoxLeft left">
                        <div class="boxTitle">天气预报</div>
                        <img src="./img/left.png" class="first_border" alt="">
                        <div class="firstBox">
                            <div class="weather-forecast" id="weatherForecast">
                                <!-- 天气预报内容将通过JavaScript动态加载 -->
                            </div>
                            <!--
                            <div class="pic">
                                <img src="img/demo_pic.png" class="first_top1" alt="">
                                <img src="img/data_pic.png" class="first_top2" alt="">
                            </div>
                            <div class="picText">
                                <span>样本图片</span>
                                <span class="text_second">茶叶病虫害大数据库</span>
                            </div>
                            <div class="voice_animation">
                                <canvas id="canvas">Your browser can not support canvas</canvas>
                            </div>
                            <div class="progress">
                                <span class="disease">茶饼病</span>
                                <span class="similar">相似度:85%</span>
                                <img src="./img/progress.gif" alt="">
                            </div>
                            <div class="about_illness">
                                <div class="symptom">
                                    <div class="symptom_title">病症症状</div>
                                    <div class="symptom_content">
                                    </div>
                                </div>
                                <div class="prevent">
                                    <div class="prevent_title">防治方法</div>
                                    <div class="prevent_content">
                                        <div>暂无防治方法信息</div>
                                    </div>
                                </div>
                            </div>
                            -->
                        </div>
                    </div>
                    <div class="baseBoxRight right">
                        <a class="navLeft" href="./mapDetails.html"><img style="" src="./img/fanhui.png" alt=""></a>

                        <!-- 地图区域替换为监控画面后的完整 -->
                        <div class="greenhouse-monitor">
                            <!-- 监控主画面 -->
                            <div class="monitor-main">
                                <div class="monitor-status">实时监控 · 在线</div>
                                <canvas id="monitor-canvas" class="monitor-img" style="width: 100%; height: 70%;"></canvas>
                                <div class="monitor-info">
                                    <span class="monitor-location" id="main-monitor-location">温室A区 - 番茄种植区</span>
                                    <span class="monitor-time" id="main-monitor-time">2025-08-28 15:30:22</span>
                                </div>
                            </div>

                            <!-- 监控摄像头切换栏 -->
                            <div class="monitor-cameras" id="monitor-cameras-container">
                                <!-- 动态生成摄像头项 -->
                            </div>

                            <!-- 底部数据栏 -->
                            <div class="monitor-data">
                                <div class="data-item">
                                    <span class="data-label">温度</span>
                                    <span class="data-value" id="temp-value">24.6℃</span>
                                    <span class="data-status normal" id="temp-status">正常</span>
                                </div>
                                <div class="data-item">
                                    <span class="data-label">湿度</span>
                                    <span class="data-value" id="humidity-value">62%</span>
                                    <span class="data-status normal" id="humidity-status">正常</span>
                                </div>
                                <div class="data-item">
                                    <span class="data-label">光照</span>
                                    <span class="data-value" id="light-value">18600lux</span>
                                    <span class="data-status warning" id="light-status">偏高</span>
                                </div>
                                <div class="data-item">
                                    <span class="data-label">CO₂</span>
                                    <span class="data-value" id="co2-value">420ppm</span>
                                    <span class="data-status normal" id="co2-status">正常</span>
                                </div>
                                <div class="data-item">
                                    <span class="data-label">土壤湿度</span>
                                    <span class="data-value" id="soil-value">45%</span>
                                    <span class="data-status normal" id="soil-status">正常</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="baseBox centerMainBox2" style="height:30%;">
                    <img src="./img/down.png" class="first_border" alt="" style="pointer-events: none;">
                    <div id="deviceHistoryContainer" style="width: 100%; height: 100%; padding: 10px 35px; box-sizing: border-box; position: relative; z-index: 10;">
                        <div class="device-history-header" style="color: #0efcff; font-size: 1vw; margin: 0 10px;">
                            设备数据
                        </div>
                        <div id="devicePropertyList" style="color: #ffffff; font-size: 1vw;">
                            <!-- 设备属性数据将在这里展示 -->
                        </div>
                    </div>
                </div>


            </div>
            <div class="leftBox right" style="width:22%">
                <div class="baseBox baseBox1" style="margin-bottom:15px;height:40%">
                    <img src="./img/right.png" class="hardware" alt="">
                    <div class="csbaseBox1">
                        <div class="boxTitle">硬件设备展示</div>
                        <ul class="boxLis">
                            <li class="left active">农业无人机</li>
                            <li class="left">田间控制器</li>
                            <li class="left">监控摄像头</li>
                            <li class="left">土壤检测仪</li>
                        </ul>
                        <div class="content1">
                            <ul>
                                <li style="display: block;" class="contList">
                                    <!-- 四个角描边 stat -->
                                    <div class="leftTopLine1"></div>
                                    <div class="leftTopLine2"></div>
                                    <div class="rightTopLine1"></div>
                                    <div class="rightTopLine2"></div>
                                    <div class="leftBottomLine1"></div>
                                    <div class="leftBottomLine2"></div>
                                    <div class="rightBottomLine1"></div>
                                    <div class="rightBottomLine2"></div>

                                    <div class="equipment_pic">
                                        <img class="first" src="img/uva.png" alt="">
                                        <img class="second" src="img/control.png" alt="">
                                        <img class="third" src="img/camera.png" alt="">
                                        <img class="fourth" src="img/detector.png" alt="">
                                    </div>
                                </li>

                            </ul>

                        </div>
                        <div class="liSpan">介绍</div>
                        <!--                        <p class="liP">-->
                        <!--                            如需商用，请联系qq:863512936</p>-->
                    </div>
                </div>
                <div class="baseBox baseBox2" style="margin-bottom:15px;height:29.5%">
                    <img src="./img/right2.png" alt="">
                    <!-- 四个角描边 end -->
                    <div class="boxTitle2">灌溉数据</div>
                    <div class="irrigate_data">
                        <div class="irrigate_top">
                            <div class="centerList">
                                <div class="centerListFont">累计灌溉水量（m2）</div>
                                <div class="centerListNum">
                                    <span class="">23678</span>
                                </div>
                            </div>
                            <div class="centerList">
                                <div class="centerListFont">灌溉压力（MPa）</div>
                                <div class="centerListNum">
                                    <span class="">0.32</span>
                                </div>
                            </div>
                        </div>
                        <div class="irrigate_bottom">
                            <div class="every_line">
                                <span>当前灌溉流量（m²/h）</span>
                                <i class="">0.78</i>
                            </div>
                            <div class="every_line">
                                <span>当前灌溉阀门数量</span>

                                <i class="counter-value">49</i>
                                <i class="counter-value">2</i>
                            </div>
                            <div class="every_line">
                                <span>茶园水池液位</span>
                                <i>2.30</i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="baseBox baseBox3" style="height:28%">
                    <img src="./img/right3.png" alt="">
                    <!-- 四个角描边 end -->
                    <div class="boxTitle2">数据日志</div>
                    <!-- <div class="data_day" id="demo" > -->
                    <div class="data_day" id="demo" style="width:100%;overflow:hidden;height: 75%;">
                        <table style="text-align: left;margin-left:10%;height:80%;">
                            <tbody id="demo1">
                                <!-- <tr class="head">
                                    <td>编号</td>
                                    <td>数据类型</td>
                                    <td>数据值</td>
                                    <td>时间</td>
                                </tr> -->
                                <tr>
                                    <td>u78</td>
                                    <td>传感器数据</td>
                                    <td>163.28</td>
                                    <td>2019年10月26日</td>
                                </tr>

                                <tr>
                                    <td>006</td>
                                    <td>无人机数据</td>
                                    <td>130.67</td>
                                    <td>2019年10月25日</td>
                                </tr>

                                <tr>
                                    <td>s07</td>
                                    <td>控制器数据</td>
                                    <td>163.28</td>
                                    <td>2019年10月25日</td>
                                </tr>
                                <tr>
                                    <td>872</td>
                                    <td>监视器数据</td>
                                    <td>130.67</td>
                                    <td>2019年10月24日</td>
                                </tr>
                            </tbody>
                            <tbody id="demo2"></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="js/jquery-3.1.1.min.js"></script>
    <script src="js/rem.js"></script>
    <script src="js/countUp.js"></script>
    <script src="js/swiper.min.js"></script>
    <script src="js/index.js"></script>
    <script src="js/new_index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/web-storage-cache@1.0.3/dist/web-storage-cache.min.js"></script>
    <script type="module">
        // 获取URL参数中的token
        function getQueryParam(name) {
            // 使用正则表达式方法获取参数
            const url = window.location.href;
            name = name.replace(/[\[\]]/g, '\\$&');
            const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
            const results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, ' '));
        }

        // 获取设备列表
        async function getDeviceList() {
            try {
                console.log('getDeviceList function called');
                
                // 首先尝试从URL参数获取token
                let token = getQueryParam('token');
                console.log('Token from URL:', token);
                
                // 如果URL中没有token，则尝试从localStorage获取
                if (!token) {
                    const wsCache = new WebStorageCache({
                        storage: 'localStorage'
                    });
                    token = wsCache.get('ACCESS_TOKEN');
                    console.log('Token from localStorage:', token);
                }
                
                // 构建URL，使用VITE_BASE_URL环境变量
                const baseUrl = import.meta.env.VITE_BASE_URL || '';
                let url = `${baseUrl}/admin-api/eiot/device/page?pageNo=1&pageSize=100`;
                console.log('Request URL:', url);
                
                // 准备请求选项
                const requestOptions = {
                    method: 'GET',
                    headers: {}
                };
                
                // 如果有token，则添加到请求头中
                if (token) {
                    requestOptions.headers['Authorization'] = `Bearer ${token}`;
                }
                console.log('Request options:', requestOptions);
                
                const response = await fetch(url, requestOptions);
                console.log('Response received:', response);
                
                // 检查响应状态
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 获取响应文本
                const text = await response.text();
                console.log('Response text:', text);
                
                // 检查返回的内容是否为HTML（登录页面）
                if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
                    console.log('Response is HTML login page');
                    return [];
                }
                
                // 尝试解析JSON
                try {
                    const result = JSON.parse(text);
                    console.log('Parsed result:', result);
                    
                    // 验证返回的数据结构
                    if (result && result.code === 0 && result.data && Array.isArray(result.data.list)) {
                        console.log('Returning device list:', result.data.list);
                        return result.data.list;
                    } else if (result && Array.isArray(result.list)) {
                        // 兼容直接返回list的格式
                        console.log('Returning device list (compatibility mode):', result.list);
                        return result.list;
                    } else {
                        console.error('返回的数据格式不正确:', result);
                        return [];
                    }
                } catch (jsonError) {
                    console.error('解析JSON失败:', jsonError);
                    throw new Error('API返回的数据不是有效的JSON格式');
                }
            } catch (error) {
                console.error('获取设备列表失败:', error);
                return [];
            }
        }

        // 获取设备属性
        async function getDeviceProperties(deviceId) {
            try {
                console.log('getDeviceProperties function called with deviceId:', deviceId);
                
                // 首先尝试从URL参数获取token
                let token = getQueryParam('token');
                console.log('Token from URL:', token);
                
                // 如果URL中没有token，则尝试从localStorage获取
                if (!token) {
                    const wsCache = new WebStorageCache({
                        storage: 'localStorage'
                    });
                    token = wsCache.get('ACCESS_TOKEN');
                    console.log('Token from localStorage:', token);
                }
                
                // 构建URL，使用VITE_BASE_URL环境变量
                const baseUrl = import.meta.env.VITE_BASE_URL || '';
                let url = `${baseUrl}/admin-api/eiot/device/getDeviceWithProperty`;
                console.log('Request URL:', url);
                
                // 准备请求选项
                const requestOptions = {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ deviceId: deviceId })
                };
                console.log('Request body:', { deviceId: deviceId });
                
                // 如果有token，则添加到请求头中
                if (token) {
                    requestOptions.headers['Authorization'] = `Bearer ${token}`;
                }
                console.log('Request options:', requestOptions);
                
                const response = await fetch(url, requestOptions);
                console.log('Response received:', response);
                
                // 检查响应状态
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 获取响应文本
                const text = await response.text();
                console.log('Response text:', text);
                
                // 检查返回的内容是否为HTML（登录页面）
                if (text.includes('<!DOCTYPE html') || text.includes('<html') || text.includes('login')) {
                    console.log('Response is HTML login page');
                    return null;
                }
                
                // 尝试解析JSON
                try {
                    const result = JSON.parse(text);
                    console.log('Parsed result:', result);
                    
                    // 验证返回的数据结构
                    if (result && result.code === 0) {
                        console.log('Returning device properties:', result.data);
                        return result.data;
                    } else if (result && result.code !== 0) {
                        console.error('API返回错误:', result.msg || '未知错误');
                        return null;
                    } else {
                        console.error('返回的数据格式不正确:', result);
                        return null;
                    }
                } catch (jsonError) {
                    console.error('解析JSON失败:', jsonError);
                    throw new Error('API返回的数据不是有效的JSON格式');
                }
            } catch (error) {
                console.error('获取设备属性失败:', error);
                return null;
            }
        }

        // 显示设备属性数据
        function displayDeviceProperties(device, properties) {
            const container = document.getElementById('devicePropertyList');
            if (!container) return;

            // 检查设备数据
            if (!device) {
                container.innerHTML = '<div>设备数据无效</div>';
                return;
            }

            // 隐藏设备名称显示
            let html = ''; // 移除设备名称显示
            
            // 检查属性数据
            if (properties && properties.identifier2property) {
                // 过滤掉 sensor 和 gateway 属性
                const filteredProperties = {};
                Object.keys(properties.identifier2property).forEach(key => {
                    const prop = properties.identifier2property[key];
                    // 检查属性是否包含 sensor 或 gateway 关键字（不区分大小写）
                    if (prop && prop.name && 
                        !prop.name.toLowerCase().includes('sensor') && 
                        !prop.name.toLowerCase().includes('gateway')) {
                        filteredProperties[key] = prop;
                    }
                });

                // 分类属性：空气、光照、土壤养分、土壤环境、水质
                const airProperties = {};
                const lightProperties = {};
                const soilNutrientProperties = {};
                const soilEnvironmentProperties = {};
                const waterProperties = {};
                
                Object.keys(filteredProperties).forEach(key => {
                    const prop = filteredProperties[key];
                    if (prop && prop.name) {
                        const name = prop.name;
                        // 空气相关属性
                        if (name.includes('空气') || 
                            (name.includes('湿度') && !name.includes('土壤')) || 
                            (name.includes('温度') && !name.includes('土壤')) || 
                            name.includes('二氧化碳') || 
                            name.includes('CO2') ||
                            name.includes('大气')) {
                            airProperties[key] = prop;
                        }
                        // 光照相关属性
                        else if (name.includes('光照') || 
                                name.includes('辐射') || 
                                name.includes('光强')) {
                            lightProperties[key] = prop;
                        }
                        // 土壤养分相关属性
                        else if (name.includes('氮') || 
                                name.includes('磷') || 
                                name.includes('钾') ||
                                name.toUpperCase().includes('N') ||
                                (name.toUpperCase().includes('P') && !name.includes('H')) ||
                                name.toUpperCase().includes('K') ||
                                name.includes('养分')) {
                            soilNutrientProperties[key] = prop;
                        }
                        // 土壤环境相关属性（包括土壤温度、土壤湿度和土壤PH）
                        else if (name.includes('土壤')) {
                            soilEnvironmentProperties[key] = prop;
                        }
                        // 水质相关属性（包括水、水PH、酸碱相关属性，但不包括土壤PH）
                        else if (name.includes('水') || 
                                name.includes('PH') || 
                                name.includes('酸碱')) {
                            waterProperties[key] = prop;
                        }
                        // 其他属性暂时不显示
                    }
                });

                // 一行展示五个类别，每个类别等宽
                html += '<div style="display: flex; gap: 10px;">';
                
                // 空气数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">💨 空气数据</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const airPropertyKeys = Object.keys(airProperties);
                if (airPropertyKeys.length > 0) {
                    airPropertyKeys.forEach(key => {
                        const prop = airProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '🔹'; // 默认图标
                            if (displayName.includes('湿度')) {
                                icon = '💧';
                            } else if (displayName.includes('温度')) {
                                icon = '🌡️';
                            } else if (displayName.includes('二氧化碳') || displayName.includes('CO2')) {
                                icon = '💨';
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无空气数据</div>';
                }
                
                html += '</div>'; // 空气数据网格结束
                html += '</div>'; // 空气数据区域结束
                
                // 光照数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">☀️ 光照数据</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const lightPropertyKeys = Object.keys(lightProperties);
                if (lightPropertyKeys.length > 0) {
                    lightPropertyKeys.forEach(key => {
                        const prop = lightProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '☀️'; // 默认图标为太阳
                            if (displayName.includes('辐射')) {
                                icon = '🔥'; // 辐射属性使用火焰图标
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无光照数据</div>';
                }
                
                html += '</div>'; // 光照数据网格结束
                html += '</div>'; // 光照数据区域结束
                
                // 土壤养分数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">🌿 土壤养分</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const soilNutrientPropertyKeys = Object.keys(soilNutrientProperties);
                if (soilNutrientPropertyKeys.length > 0) {
                    soilNutrientPropertyKeys.forEach(key => {
                        const prop = soilNutrientProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '🌿'; // 默认图标为植物
                            if (displayName.includes('氮') || displayName.toUpperCase().includes('N')) {
                                icon = '🌿'; // 氮元素 - 用植物符号表示
                            } else if (displayName.includes('磷') || (displayName.toUpperCase().includes('P') && !displayName.includes('H'))) {
                                icon = '🦴'; // 磷元素 - 用骨头符号表示
                            } else if (displayName.includes('钾') || displayName.toUpperCase().includes('K')) {
                                icon = '🍌'; // 钾元素 - 用香蕉符号表示
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无土壤养分数据</div>';
                }
                
                html += '</div>'; // 土壤养分数据网格结束
                html += '</div>'; // 土壤养分数据区域结束
                
                // 土壤环境数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">🌱 土壤环境</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const soilEnvironmentPropertyKeys = Object.keys(soilEnvironmentProperties);
                if (soilEnvironmentPropertyKeys.length > 0) {
                    soilEnvironmentPropertyKeys.forEach(key => {
                        const prop = soilEnvironmentProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '🌱'; // 默认图标为幼苗
                            if (displayName.includes('湿度')) {
                                icon = '💧';
                            } else if (displayName.includes('温度')) {
                                icon = '🌡️';
                            } else if (displayName.includes('PH')) {
                                icon = '🧪'; // 土壤PH使用试管图标表示酸碱度
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无土壤环境数据</div>';
                }
                
                html += '</div>'; // 土壤环境数据网格结束
                html += '</div>'; // 土壤环境数据区域结束
                
                // 水质数据列
                html += '<div style="flex: 1;">';
                html += '<h3 style="color: #0efcff; margin-bottom: 10px; font-size: 1.0vw;">💧 水质数据</h3>';
                html += '<div style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 3px;">';
                
                const waterPropertyKeys = Object.keys(waterProperties);
                if (waterPropertyKeys.length > 0) {
                    waterPropertyKeys.forEach(key => {
                        const prop = waterProperties[key];
                        if (prop) {
                            let displayName = prop.name || key;
                            let displayValue = prop.value !== undefined && prop.value !== null ? prop.value : '';
                            
                            let icon = '💧'; // 默认图标为水滴
                            if (displayName.includes('PH') || displayName.includes('酸碱')) {
                                icon = '🧪'; // 水PH使用试管图标表示酸碱度
                            }
                            
                            html += `
                                <div style="background: rgba(14, 252, 255, 0.1); padding: 3px; border-radius: 2px; border: 1px solid rgba(14, 252, 255, 0.3); font-size: 0.7vw;">
                                    <div style="font-weight: bold; margin-bottom: 2px; font-size: 0.8vw;"><span style="font-size: 1.2vw;">${icon}</span> ${displayName}：${displayValue}</div>
                                </div>
                            `;
                        }
                    });
                } else {
                    html += '<div style="grid-column: span 1;">暂无水质数据</div>';
                }
                
                html += '</div>'; // 水质数据网格结束
                html += '</div>'; // 水质数据区域结束
                
                html += '</div>'; // 整体flex容器结束
                
            } else {
                html += '<div>暂无属性数据</div>';
            }
            
            container.innerHTML = html;
        }

        // 防抖函数
        function debounce(func, delay) {
            let timeoutId;
            return function (...args) {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => func.apply(this, args), delay);
            };
        }

        // 加载第一个设备的属性数据
        async function loadFirstDeviceProperties() {
            try {
                // 获取设备列表
                const devices = await getDeviceList();
                const container = document.getElementById('devicePropertyList');
                if (!container) return;
                
                if (!Array.isArray(devices) || devices.length === 0) {
                    container.innerHTML = '<div>暂无设备数据</div>';
                    return;
                }

                // 直接加载第一个设备的属性
                const firstDevice = devices[0];
                const properties = await getDeviceProperties(firstDevice.id);
                displayDeviceProperties(firstDevice, properties);
            } catch (error) {
                console.error('加载设备属性数据失败:', error);
                const container = document.getElementById('devicePropertyList');
                if (container) {
                    container.innerHTML = '<div>加载设备数据失败: ' + error.message + '</div>';
                }
            }
        }

        // 获取当前时间并格式化
        function getCurrentTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 更新监控时间显示
        function updateMonitorTime() {
            document.getElementById('main-monitor-time').textContent = getCurrentTime();
        }

        // 定时更新时间
        setInterval(updateMonitorTime, 1000);

        // 存储摄像头数据
        let camerasData = [];
        let currentPlayer = null;

        // 获取视频监控数据
        async function fetchCamerasData() {
            try {
                // 获取token
                let token = getQueryParam('token');
                
                // 如果URL中没有token，则尝试从localStorage获取
                if (!token) {
                    const wsCache = new WebStorageCache({
                        storage: 'localStorage'
                    });
                    token = wsCache.get('ACCESS_TOKEN');
                }
                
                // 构建URL，使用VITE_BASE_URL环境变量
                const baseUrl = import.meta.env.VITE_BASE_URL || '';
                const url = `${baseUrl}/admin-api/sp/SHP/page?pageNo=1&pageSize=8`;
                
                // 准备请求选项
                const requestOptions = {
                    method: 'GET',
                    headers: {}
                };
                
                // 如果有token，则添加到请求头中
                if (token) {
                    requestOptions.headers['Authorization'] = `Bearer ${token}`;
                }
                
                const response = await fetch(url, requestOptions);
                const data = await response.json();
                
                if (data.code === 0) {
                    camerasData = data.data.list;
                    renderCameras(camerasData);
                    // 默认播放第一个摄像头
                    if (camerasData.length > 0) {
                        playCamera(camerasData[0]);
                        updateMainCameraInfo(camerasData[0]);
                        updateSensorData(camerasData[0]);
                    }
                }
            } catch (error) {
                console.error('获取摄像头数据失败:', error);
                // 使用默认数据进行演示
                useDefaultCameras();
            }
        }



        // 渲染摄像头列表
        function renderCameras(cameras) {
            const container = document.getElementById('monitor-cameras-container');
            container.innerHTML = '';
            
            cameras.forEach((camera, index) => {
                const cameraItem = document.createElement('div');
                cameraItem.className = `camera-item ${index === 0 ? 'active' : ''}`;
                cameraItem.dataset.cam = camera.id;
                
                cameraItem.innerHTML = `
                    <img src="${camera.imageAddress}" alt="${camera.spNumber}缩略图">
                    <span>${camera.spNumber}</span>
                `;
                
                cameraItem.addEventListener('click', () => {
                    // 移除所有active类
                    document.querySelectorAll('.camera-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    // 为当前项添加active类
                    cameraItem.classList.add('active');
                    // 播放选中的摄像头
                    playCamera(camera);
                    // 更新主画面信息
                    updateMainCameraInfo(camera);
                    // 更新传感器数据
                    updateSensorData(camera);
                });
                
                container.appendChild(cameraItem);
            });
        }

        // 播放指定摄像头
        function playCamera(camera) {
            const canvas = document.getElementById('monitor-canvas');
            
            // 如果已有播放器，先停止
            if (currentPlayer) {
                currentPlayer.destroy();
            }
            
            // 创建新的播放器实例
            // 注意：这里的端口需要与serve/index.js中配置的端口一致
            try {
                currentPlayer = new JSMpeg.Player(`ws://localhost:8033/rtsp?url=${btoa(camera.spaddress)}`, {
                    canvas: canvas
                });
            } catch (error) {
                console.error('播放视频失败:', error);
                // 显示默认图片
                const ctx = canvas.getContext('2d');
                ctx.fillStyle = '#000';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                ctx.font = '20px Arial';
                ctx.fillStyle = '#fff';
                ctx.textAlign = 'center';
                ctx.fillText('视频加载中...', canvas.width/2, canvas.height/2);
            }
        }

        // 更新主画面信息
        function updateMainCameraInfo(camera) {
            document.getElementById('main-monitor-location').textContent = camera.spNumber;
        }

        // 更新传感器数据
        function updateSensorData(camera) {
            document.getElementById('temp-value').textContent = camera.cgqNumber1 + '℃';
            document.getElementById('humidity-value').textContent = camera.cgqNumber2 + '%';
            document.getElementById('light-value').textContent = camera.cgqNumber3 + 'lux';
            document.getElementById('co2-value').textContent = camera.cgqNumber4 + 'ppm';
            document.getElementById('soil-value').textContent = camera.cgqNumber5 + '%';
            
            // 更新状态显示（简单示例）
            updateStatus('temp-status', camera.cgqNumber1 < 20 ? '偏低' : camera.cgqNumber1 > 30 ? '偏高' : '正常');
            updateStatus('humidity-status', camera.cgqNumber2 < 50 ? '偏低' : camera.cgqNumber2 > 70 ? '偏高' : '正常');
            updateStatus('light-status', camera.cgqNumber3 < 10000 ? '偏低' : camera.cgqNumber3 > 20000 ? '偏高' : '正常');
            updateStatus('co2-status', camera.cgqNumber4 < 300 ? '偏低' : camera.cgqNumber4 > 500 ? '偏高' : '正常');
            updateStatus('soil-status', camera.cgqNumber5 < 30 ? '偏低' : camera.cgqNumber5 > 60 ? '偏高' : '正常');
        }

        // 更新状态显示
        function updateStatus(elementId, status) {
            const element = document.getElementById(elementId);
            element.textContent = status;
            element.className = 'data-status ' + (status === '正常' ? 'normal' : 'warning');
        }

        // 页面加载完成后获取摄像头数据
        document.addEventListener('DOMContentLoaded', function() {
            fetchCamerasData();
            updateMonitorTime();
        });

        // 使用中国天气网免费API获取商丘实时天气数据
        const city = '商丘';
        const url = `http://wthrcdn.etouch.cn/weather_mini?city=${encodeURIComponent(city)}`;
        
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 检查是否有错误码
                if (data && data.status !== 1000) {
                    console.error('天气API返回错误:', data.desc || '未知错误');
                    // 显示默认天气数据
                    displayDefaultWeather();
                    return;
                }
                
                if (data && data.status === 1000 && data.data) {
                    // 转换数据格式以匹配原有的显示函数
                    const convertedData = {
                        code: '200',
                        now: {
                            temp: data.data.wendu,
                            text: data.data.forecast[0].type,
                            windDir: '未知',
                            windScale: '未知',
                            humidity: '未知',
                            pressure: '未知',
                            vis: '未知',
                            feelsLike: data.data.wendu,
                            obsTime: new Date().toISOString()
                        }
                    };
                    displayRealTimeWeatherData(convertedData);
                } else {
                    // 如果API不可用，显示默认数据
                    console.warn('天气API返回数据格式不正确:', data);
                    displayDefaultWeather();
                }
            })
            .catch(error => {
                console.error('获取天气数据失败:', error);
                // 如果获取数据失败，显示默认数据
                displayDefaultWeather();
            });
    </script>
</body>
</html>
